#
# Copyright 2008 Wepoco.  http://www.wepoco.org/
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import cgi
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from Track import Track
from bz2 import compress
from xml.etree.ElementTree import parse
from template import header, footer
from StringIO import StringIO

class Upload(webapp.RequestHandler):
  def post(self):
    track = Track()

    form = cgi.FieldStorage()
    content = form['file']
    parts =  content.filename.rsplit("\\",1)
    track.name = parts[-1]
    data = content.file.read()

    if len(data) == 0:
        self.redirect('/')
        return

    isGPX = False
    try:
      tree =  parse(StringIO(data))
      root = tree.getroot()
      (ns,tag) = root.tag[1:].split("}")
      if tag == 'gpx':
        isGPX = True
        pass
    except:
      pass
    
    if isGPX:
      if users.get_current_user():
          track.user = users.get_current_user()
          track.content = compress(data)
      track.isPublic = False
      # Current time will be used until XML is parsed
      # and start time of track determined 
      track.isStartTime = False
      track.put()
      self.redirect('/')
    else:
      self.response.out.write(header(self.request))
      self.response.out.write("""<H3>Sorry, not a valid GPX file.</H3>""")
      self.response.out.write(footer(self.request))
      pass

    return



